import { Request, Response } from 'express';
import * as menuData from './utils/menuData'

// 代码中会兼容本地 service mock 以及部署站点的静态数据
export default {
  // 支持值为 Object 和 Array
  'GET /api/menuList': (req: Request, res: Response) => {
    const { name } = req.query;
    menuData.selectMenu({ name }).then(data => {
      res.send({
        success: true,
        data,
      })
    }).catch(err => {
      res.status(500).send({
        data: {
          err,
        },
        errorCode: '500',
        errorMessage: '数据库错误：' + JSON.stringify(err),
        success: false,
      });
    })
  },
  'POST /api/addMenu': (req: Request, res: Response) => {
    menuData.insertMenu(req.body).then(data => {
      res.send({
        success: true,
        data,
      })
    }).catch(err => {
      res.status(500).send({
        data: {
          err,
        },
        errorCode: '500',
        errorMessage: '数据库错误：' + JSON.stringify(err),
        success: false,
      });
    })
  },
  'POST /api/editMenu': (req: Request, res: Response) => {
    menuData.updateMenu(req.body).then(data => {
      res.send({
        success: true,
        data,
      })
    }).catch(err => {
      res.status(500).send({
        data: {
          err,
        },
        errorCode: '500',
        errorMessage: '数据库错误：' + JSON.stringify(err),
        success: false,
      });
    })
  },

  'GET /api/deleteMenu': (req: Request, res: Response) => {
    menuData.deleteMenu(req.query.id).then(data => {
      res.send({
        success: true,
        data,
      })
    }).catch(err => {
      res.status(500).send({
        data: {
          err,
        },
        errorCode: '500',
        errorMessage: '数据库错误：' + JSON.stringify(err),
        success: false,
      });
    })
  },
};
